package site.brood.gateway.filter;


import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import site.brood.common.core.jwt.JwtUtil;
import site.brood.common.core.str.StrUtil;
import site.brood.common.core.web.ServletUtil;
import site.brood.common.core.constant.Constants;
import site.brood.common.core.web.HttpStatus;
import site.brood.common.redis.service.RedisService;
import site.brood.gateway.properties.IgnoreWhiteProperties;

/**
 * 网关鉴权过滤器
 * 外部网络请求流程：
 * 外部网络请求header中带jwt格式token
 * 一、经过网关服务
 * 在网关拦截器中，从jwt中取出userId,userName,userKey，转存到header中，转发给业务微服务
 * 二、内部微服务
 * 1)在请求头拦截器中，取出header中的userId,userName,userKey，转存到TransmittableThreadLocal对象中
 * 通过userKey从redis中取出用户详情，以userKey为key存入TransmittableThreadLocal对象中
 * 2)调用内部feign服务(例如：日志服务)
 * 在feign拦截器中，从主线程request中或TransmittableThreadLocal对象中取出userId,userName,userKey，转存到feign header中
 * 三、日志服务
 * 1)在鉴权注解(RequiresPermissions)的AOP回调中，从TransmittableThreadLocal对象中取出userId,userName,userKey
 * 通过userKey从TransmittableThreadLocal对象中取出用户详情
 * 通过用户详情中的权限列表，与鉴权注解中要求的权限数组比对
 * 鉴权失败抛出鉴权失败异常
 * 四、全局异常AOP
 * 将鉴权失败异常转为AjaxJson对象写入网络response
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered
{
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
    {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的白名单路径:
        // /auth/logout
        // /auth/login
        // /auth/register
        // /*/v2/api-docs
        // /csrf
        if (StrUtil.matches(url, ignoreWhite.getWhites()))
        {
            return chain.filter(exchange);
        }
        // 从请求头中获取token
        String token = getToken(request);
        if (StrUtil.isEmpty(token))
        {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        // 解析jwt格式token
        Claims claims = JwtUtil.parseToken(token);
        if (claims == null)
        {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }

        // 从jwt中取出redis放用户详情的key
        // key要去掉前缀:'Bearer '
        String userkey = JwtUtil.getUserCacheKey(claims);
        boolean islogin = redisService.hasKey(getTokenKey(userkey));
        if (!islogin)
        {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        // 从jwt中取出userid、username
        String userid = JwtUtil.getUserId(claims);
        String username = JwtUtil.getUsername(claims);
        if (StrUtil.isEmpty(userid) || StrUtil.isEmpty(username))
        {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

        // 将用户id、用户名称、redis存用户详情的key写入内部请求头中
        // 供内部微服务验证权限使用
        addHeader(mutate, Constants.INNER_HEADER_USER_ID, userid);
        addHeader(mutate, Constants.INNER_HEADER_USER_NAME, username);
        addHeader(mutate, Constants.INNER_HEADER_USER_CACHE_KEY, userkey);
        // 清除掉请求头中的from-source字段，防止外部请求假冒内部请求，跳过权限验证
        // 内部服务之间调用在请求头中加了from-source=inner字段，标识内部请求
        // 某些服务只暴露给内部请求，有内部请求标识的请求不会验证权限
        removeHeader(mutate, Constants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
    {
        if (value == null)
        {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtil.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtil.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return Constants.CACHE_LOGIN_TOKEN_KEY_PREFIX + token;
    }

    /**
     * 获取请求头中的token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(Constants.OUTTER_HEAD_TOKEN);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(Constants.OUTTER_HEAD_TOKEN_PREFIX))
        {
            token = token.replaceFirst(Constants.OUTTER_HEAD_TOKEN_PREFIX, StrUtil.EMPTY);
        }
        return token;
    }

    @Override
    public int getOrder()
    {
        return -200;
    }
}
